package com.yhy.shiro.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.HashSet;
import java.util.Set;

import com.yhy.shiro.entity.User;

public class UserDao {
	private Connection con = null;

	public UserDao(Connection con) {
		this.con = con;
	}

	// 获取用户信息
	public User getUserByName(String userName) throws Exception {
		User user = null;

		String sql = "select * from t_user where userName=?";
		PreparedStatement pstmt = this.con.prepareStatement(sql);
		pstmt.setString(1, userName);
		ResultSet rs = pstmt.executeQuery();

		// 获取 User 的信息
		if (rs.next()) {
			user = new User();
			user.setId(rs.getInt("id"));
			user.setUserName(rs.getString("userName"));
			user.setPassword(rs.getString("password"));
			Integer roleId = rs.getInt("roleId");
//			user.setRoleId(rs.getInt("roleId"));
			user.setRoleId(roleId);
		}
		return user;
	}

	// 获取角色名
	public String getRoleName(String userName) throws Exception {
		String roleName = null;
		String sql = "select * from t_user as u, t_role as r  where u.roleId=r.id and u.userName = ?";
		PreparedStatement pstmt = this.con.prepareStatement(sql);
		pstmt.setString(1, userName);
		ResultSet rs = pstmt.executeQuery();

		// 获取角色名
		if (rs.next()) {
			roleName = rs.getString("roleName");
		}

		return roleName;
	}

	// 获取权限列表
	public Set<String> getPerminssions(int roleId) throws Exception {
		Set<String> permissions = new HashSet<String>();
		String sql = "select * from t_role as r, t_permission as p  where p.roleId=r.id and r.id=?";
		PreparedStatement pstmt = this.con.prepareStatement(sql);
		pstmt.setInt( 1, roleId );
		ResultSet rs = pstmt.executeQuery();

		// 获取权限列表
		while (rs.next()) {
			permissions.add(rs.getString("permissionName"));
		}
		return permissions;
	}
}
